/*
 * threading-nix.cpp
 *
 *  Created on: May 19, 2012
 *      Author: burek
 */

#ifndef WIN32

#include "threading.h"
#include <stdlib.h>
#include <time.h>

#include <pthread.h>
#include <signal.h>

CUThread * cu_spawnThread(CTFPTR func, void * param)
{
	CUThread * thread = (CUThread*) malloc(sizeof(CUThread));
	int result = pthread_create(&(thread->nix_handle), NULL, func, param);
	if(result == 0)
	{
		thread->state = CUT_RUNNING;
		return thread;
	}
	else
	{
		free(thread);
		return NULL;
	}
}

int cu_joinThread(CUThread * thread)
{
	if(thread == NULL) return CU_ERROR;

	if(pthread_join(thread->nix_handle, NULL) == 0)
		return CU_OK;
	else
		return CU_ERROR;
}

void cu_sleep(int ms)
{
	struct timespec req={0},rem={0};
	time_t sec=(int)(ms/1000);
	ms=ms-(sec*1000);
	req.tv_sec=sec;
	req.tv_nsec=ms*1000000L;
	nanosleep(&req, &rem);
}

CUMutex * cu_createMutex()
{
	CUMutex * m = (CUMutex*)calloc(1, sizeof(CUMutex));
	return m;
}

void cu_lockMutex(CUMutex * m)
{
	m->state = 2;
	pthread_mutex_lock(&(m->nix_mutex));
	m->state = 1;
}

void cu_unlockMutex(CUMutex * m)
{
	pthread_mutex_unlock(&(m->nix_mutex));
	m->state = 0;
}

int cu_killThread(CUThread * thread)
{
	if(thread == NULL) return CU_ERROR;
	if(pthread_kill(thread->nix_handle, 9) == 0)
		return CU_OK;
	else
		return CU_ERROR;
}

int cu_getCurrentThreadID()
{
	return (int)pthread_self();
}

#endif
